package com.jinxin.platform.cdacsrecord.core.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.base.common.annotation.RegBusiness;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.*;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.Constant;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.ResultEntity;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.AcsBlockStatInfoVO;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.DataResult2;
import com.jinxin.platform.cdacsrecord.core.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2020-08-24
 * @Author: Lingnan
 **/
@RegBusiness(moduleKey = Constant.MODULE_KEY, className = "OpenStatisticsRpcService")
@Slf4j
@Service
public class OpenDoorRpcService {
    @Autowired
    private RestTemplateService restTemplateService;
    @Autowired
    private AcsControlUserInfoService userInfoService;
    @Autowired
    private JurenAcsCommunityService acsCommunityService;
    @Autowired
    private AcsControlBlockInfoService blockInfoService;
    @Autowired
    private AcsControlRoomInfoService roomInfoService;
    @Autowired
    private JurenAcsOpenRecordService recordService;
    @Value("${cdacsrecord.account-info.companyId}")
    private String COMPANYID;

    // 获取开门的统计信息，出入流量和访客数量统计
    public JsonResult getOpenStatistics(Map param){
        OpenRecordParam recordParam = new OpenRecordParam();
        recordParam.setPage(1);
        recordParam.setRows(10000);
        Map<String,Object> resultMap = new HashMap<>();
        String companyId = param.containsKey("companyId") ? (String) param.get("companyId") : COMPANYID;
        ResultEntity resultEntity = restTemplateService.listOpenRecord(recordParam,companyId);
        long openCount = 0,visitorCount = 0;
        if(resultEntity != null){
            log.info("getOpenStatistics: " + resultEntity.toString());
            DataResult2 dataResult = (DataResult2)resultEntity.getResultContent();
            openCount = dataResult.getRecords() != null ? dataResult.getRecords() : 0;
            JSONArray jsonArray = dataResult.getRows();
            if(jsonArray != null){
                List<Integer> listTemp = new ArrayList();
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    JurenOpenRecordInfo info = JSON.parseObject(JSON.toJSONString(jsonObject), JurenOpenRecordInfo.class);
                    JSONObject wyUser = info.getWyUser();
                    if(wyUser != null){
                        WyUserInfo wyUserInfo = JSON.parseObject(JSON.toJSONString(wyUser), WyUserInfo.class);
                        if(wyUserInfo != null){
                            if(!listTemp.contains(wyUserInfo.getWyUserId())){
                                listTemp.add(wyUserInfo.getWyUserId());
                            }
                        }
                    }
                }
                visitorCount = listTemp.size();
            }
        }
        resultMap.put("openCount", openCount);
        resultMap.put("visitorCount", visitorCount);
        return JsonResult.ok(resultMap);
    }

    /**
     * 获取开门记录
     * @param param
     * @return
     */
    public JsonResult getOpenDoorRecords(Map param){
        OpenRecordParam recordParam = new OpenRecordParam();
        Integer userType = param.containsKey("userType") ? Integer.parseInt((String)param.get("userType")) : recordParam.getUserType();
        Integer wyUserType = param.containsKey("wyUserType") ? Integer.parseInt((String)param.get("wyUserType")) : recordParam.getWyUserType();
        Integer page = param.containsKey("page") ? Integer.parseInt((String)param.get("page")) : recordParam.getPage();
        Integer rows = param.containsKey("rows") ? Integer.parseInt((String)param.get("rows")) : recordParam.getRows();
        String startDate = param.containsKey("startDate") ? (String)param.get("startDate") : "";
        String endDate = param.containsKey("endDate") ? (String)param.get("endDate") : "";
        String companyId = param.containsKey("companyId") ? (String) param.get("companyId") : COMPANYID;
        recordParam.setUserType(userType);
        recordParam.setWyUserType(wyUserType);
        recordParam.setPage(page);
        recordParam.setRows(rows);
        Map<String,Object> resultMap = new HashMap<>();
        ResultEntity resultEntity = restTemplateService.listOpenRecord(recordParam,companyId);
        long openCount = 0;
        List<JurenOpenRecordInfo> list = new ArrayList();
        if(resultEntity != null){
            log.info("getOpenStatistics: " + resultEntity.toString());
            DataResult2 dataResult = (DataResult2)resultEntity.getResultContent();
            openCount = dataResult.getRecords() != null ? dataResult.getRecords() : 0;
            JSONArray jsonArray = dataResult.getRows();
            if(jsonArray != null){
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    JurenOpenRecordInfo info = JSON.parseObject(JSON.toJSONString(jsonObject), JurenOpenRecordInfo.class);
                    JSONObject wyUser = info.getWyUser();
                    if(wyUser != null){
                        WyUserInfo wyUserInfo = JSON.parseObject(JSON.toJSONString(wyUser), WyUserInfo.class);
                        if(wyUserInfo != null){
                            info.setWyUserName(wyUserInfo.getWyUserName());
                            info.setWyUserType(wyUserInfo.getWyUserType());
                        }
                    }
                    list.add(info);
                }
            }
        }
        resultMap.put("count", openCount);
        resultMap.put("records", list);
        return JsonResult.ok(resultMap);
    }

    /**
     * 获取所有的社区用户信息
     * @return
     */
    public JsonResult listUsersByCondition(Map param){
        return JsonResult.ok(userInfoService.selectAllUsers());
    }

    /**
     * 获取所有房间的用户信息
     * @return
     */
    public JsonResult listRoomOwners(Map param){
        log.info("=======获取所有房间的用户信息 listRoomOwners ");
        List<RoomDto> roomDtoList = userInfoService.selectOwners();
        log.info("结果 ==> {}", roomDtoList);
        return JsonResult.ok(roomDtoList);
    }

    /**
     * 获取社区列表
     * @return
     */
    public JsonResult listCommunities(Map param){
        return JsonResult.ok(acsCommunityService.listCommunities());
    }

    /**
     * 根据小区id获取楼栋列表
     * @return
     */
    public JsonResult listBlocksById(Map param){
        String communityId = param.containsKey("communityId") ? (String) param.get("communityId") : "";
        if(StringUtils.isEmpty(communityId)){
            return JsonResult.error("小区id不能为空");
        }
        List<AcsBlockStatInfoVO> blockStatInfoVOList = blockInfoService.listStatBlcokInfo(communityId);
        return JsonResult.ok(blockStatInfoVOList);
    }

    /**
     * 根据楼栋id获取房间列表
     * @return
     */
    public JsonResult listRoomsId(Map param){
        String blockId = param.containsKey("blockId") ? (String) param.get("blockId") : "";
        if(StringUtils.isEmpty(blockId)){
            return JsonResult.error("楼栋id不能为空");
        }
        AcsControlRoomInfoDO paramDO = new AcsControlRoomInfoDO();
        paramDO.setBlockId(blockId);
        List<AcsControlRoomInfoDO> RoomInfoDOS = roomInfoService.selDOByInfo(paramDO);
        return JsonResult.ok(RoomInfoDOS);
    }

    /**
     * 根据楼栋id获取社区用户信息列表
     * @return
     */
    public JsonResult listUsersById(Map param){
        String blockId = param.containsKey("blockId") ? (String) param.get("blockId") : "";
        if(StringUtils.isEmpty(blockId)){
            return JsonResult.error("楼栋id不能为空");
        }
        AcsControlUserInfoDO paramDO = new AcsControlUserInfoDO();
        paramDO.setUserBlockId(blockId);
        return JsonResult.ok(userInfoService.selDOByInfo(paramDO, ""));
    }

    /**
     * 根据用户id 时间等查询开门记录
     * @param param
     * @return
     */
    public JsonResult getOpenRecordCountById(Map param){
        String startDate = param.containsKey("startTime") ? (String)param.get("startTime") : "";
        String endDate = param.containsKey("endTime") ? (String)param.get("endTime") : "";
        String wyUserId = param.containsKey("userId") ? (String) param.get("userId") : "";
        HashMap param2 = new HashMap();
        param2.put("startDate",startDate);
        param2.put("endDate",endDate);
        param2.put("wyUserId",wyUserId);
        int count = recordService.listPageCount(param2);
        return JsonResult.ok(String.valueOf(count));
    }

    public JsonResult getFaceInfoById(Map param){
        log.info("=======根据用户id获取人脸信息 ");
        String userId = param.containsKey("userId") ? (String)param.get("userId") : "";
        return userInfoService.getFaceInfoById(userId);
    }
}
